/**
 * 
 */
package acmCoder.migu;

import java.util.Scanner;

/**
 * @author zhongfang
 *
 */
public class 打字 {

	static int[][] dp;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int T = scanner.nextInt();
		scanner.nextLine();
		while (T-- > 0) {
			String string = scanner.nextLine();
			dp = new int[string.length()][2];
			int r = getRes(string, 0, true);
			// int r = getRes2(string);
			System.out.println(r);
		}
	}

	private static int getRes2(String string) {
		boolean tag = true;
		int count = 0;
		for (int i = 0; i < string.length(); i++) {
			if (Character.isLowerCase(string.charAt(i)) == tag) {
				count++;
			} else {
				count += 2;
				tag = !tag;
			}
		}
		return count;
	}

	private static int getRes(String string, int i, boolean curStatus) {// true代表当前状态是小写
		if (i == string.length()) {
			return 0;
		}
		int state = curStatus ? 0 : 1;
		if (dp[i][state] != 0) {
			return dp[i][state];
		}
		boolean lower = Character.isLowerCase(string.charAt(i));
		if (lower == curStatus) {
			dp[i][state] = 1 + getRes(string, i + 1, curStatus);
		} else {
			boolean change = (!curStatus);
			dp[i][state] = 2 + Math.min(getRes(string, i + 1, curStatus), getRes(string, i + 1, change));
		}
		return dp[i][state];
	}

}
